package com.siyoumi.app.modules.app_book.admin;

import com.siyoumi.app.entity.BookSku;
import com.siyoumi.app.entity.BookSkuDay;
import com.siyoumi.app.entity.BookSpu;
import com.siyoumi.app.modules.app_book.service.SvcBookSku;
import com.siyoumi.app.modules.app_book.service.SvcBookSpu;
import com.siyoumi.app.modules.app_book.vo.SkuDayData;
import com.siyoumi.app.modules.app_book.vo.SpuDayData;
import com.siyoumi.component.http.InputData;
import com.siyoumi.controller.AdminApiController;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.util.XDate;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/xadmin/app_book/app_book__sku_day__list")
public class app_book__sku_day__list
        extends AdminApiController {
    @GetMapping()
    public XReturn index() {
        String skuId = input("sku_id");
        String month = input("month");
        if (XStr.isNullOrEmpty(month)) {
            month = XDate.format(XDate.now(), "yyyy-MM");
        }
        setPageFrom("month", month);


        XValidator.isNullOrEmpty(skuId, "miss sku_id");
        BookSku entitySku = SvcBookSku.getApp().getEntity(skuId);
        XValidator.isNull(entitySku, "sku_id error");
        BookSpu entitySpu = SvcBookSpu.getApp().getEntity(entitySku.getBsku_spu_id());

        setPageTitle(entitySpu.getBspu_name(), "-", entitySku.skuName(), "-每日价格");

        InputData inputData = InputData.fromRequest();

        LocalDateTime b = XDate.parse(month + "-01");
        LocalDateTime e = b.plusMonths(1).minusDays(1);
        //数据库加价列表
        List<SkuDayData> listDay = SvcBookSku.getBean().listDay(entitySku, b, e);
        Map<String, Object> mapDateList = new LinkedHashMap<>();
        for (SkuDayData entity : listDay) {
            mapDateList.put(XDate.toDateString(entity.getDate()), entity);
        }

        getR().setData("list", mapDateList);
        getR().setData("count", listDay.size());
        //sku列表
        {
            String[] select = {
                    "bsku_id",
                    "bsku_day",
            };
            JoinWrapperPlus<BookSku> query = SvcBookSku.getBean().listQuery(List.of(entitySku.getBsku_spu_id()));
            query.orderByAsc("bsku_day");
            query.select(select);
            setPageInfo("list_sku", SvcBookSku.getApp().get(query));
        }

        return getR();
    }
}
